package top.liuzhenyu.springboot3.aop;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import top.liuzhenyu.springboot3.annotation.Limit;
import top.liuzhenyu.springboot3.exception.AppException;
import top.liuzhenyu.springboot3.service.LimitService;

@Aspect
@Slf4j
@Component
@RequiredArgsConstructor
@Order(20)
public class ControllerLimit implements ControllerPointCut {
    private final LimitService limitService;

    @Before("pointcat()")
    public void before(JoinPoint jp) {
        // 控制器的切点都是定义在方法上的，所以签名一定是方法
        MethodSignature ms = (MethodSignature) jp.getSignature();
        Limit limit = ms.getMethod().getAnnotation(Limit.class);
        log.debug("limit信息：{}", limit);
        if (limit == null) {
            log.debug("无需限流");
            return;
        }
        if (!limitService.check(limit)) {
            throw AppException.create(limit.message(), 600);
        }
    }
}
